import http from '@/api';
/**
 * 对应参数配置标识
 * - 设置url的值
 *    "id":"url=>configPageParams.tableRefs.proTableBox.clickRow.id"
 * - 设置动态值
 *    "id":${configPageParams.xxx}
 * - 设置默认值
 *    "id":"o"
 * - 查询验证
 *     "validationField":"id" ||  "validationField":"id,id不能为空" 两种配置
 *
 */

/** 设置表格请求相关配置 */
export const setRequestApi = (json, tableData, configPageParams) => {
  const { initParam, requestApiProps, requestAuto, pagination, dataCallback } = json || {};

  // 没有请求api直接跳过
  if (!requestApiProps) {
    Object.assign(tableData, {
      requestApi: null,
      requestAuto: false
    });
    return;
  }
  // console.log(requestApiProps, 'requestApiProps===============');

  const { type, url, data, validationField, validationMessage } = requestApiProps || {};

  if (dataCallback) {
    const back = new Function('data', 'configPageParams', dataCallback);
    tableData.dataCallback = data => back(data, configPageParams);
  }

  Object.assign(tableData, {
    requestApi: params => {
      let _url = url;
      let _params = {};

      // console.log(data, 'data');

      if (data) {
        console.log(configPageParams, 'configPageParams');

        const newData = setParams(JSON.parse(data), _url, configPageParams);
        console.log(newData, 'newData');

        _url = newData.url;
        _params = newData.params;
      }

      // console.log(_params, 'newData', validationField);

      if (validationField) {
        const v = validationField.split(';');
        for (let key of v) {
          const [k, message] = key.split(',');
          if (!_params[k]) {
            const m = message || validationMessage || `${key}不能为空`;
            elMessage(m, 'warning');
            return;
          }
        }
      }

      return http[type](_url, Object.assign(_params, params) || {});
    },

    requestApiProps,
    // 配置是否自动请求数据
    requestAuto: requestAuto ?? true,
    // 是否分页
    pagination: pagination ?? true,
    // 初始化参数请求参数+默认参数
    initParam: Object.assign(initParam ? JSON.parse(initParam) : {}, setDefaultData(data))
  });
};

/** 其他主表格点击事件(有明细表格必有一个点击事件) */
export const setMainTableClick = (json, tableData, mainData, configPageParams) => {
  Object.assign(tableData, { detailLabel: json.detailLabel, detailName: json.ref });
  if (!mainData.mainTableData?.rowClick) {
    // 如果没有点击事件但是有明细默认调用目前显示的明细表格
    mainData.mainTableData.rowClick = (row, column: any) => {
      // 点击的是操作栏不触发点击事件
      if (column?.label === 'operation') return;
      configPageParams.tableRefs[mainData.detailsTableData.activeName].search();
    };
  }
};

/**设置表格属性 */
export function setAttrs(json, tableData, attrsField = 'attrs-') {
  let tableAttrs = {};
  Object.keys(json).forEach(key => {
    // 表格的全局属性 获取所有表格的全局属性
    if (key.includes(attrsField)) {
      const k = key.replace(attrsField, '');
      tableAttrs[k] = json[key];
    }
  });
  return tableAttrs;
}

/**设置默认值 */
const setDefaultData = data => {
  let obj = {};
  if (data) {
    const json = JSON.parse(data);
    Object.keys(json).forEach(key => {
      const value: string = json[key];
      if (!value.includes('$') && !value.includes('url=>')) {
        obj[key] = value;
      }
    });
  }
  return obj;
};

/**
 * 设置请求参数
 * "data":{
      // 设置url的值
      "id":"url=>configPageParams.tableRefs.proTableBox.clickRow.id",
      // 设置动态值
      "id":$configPageParams.xxx,
      // 设置默认值
      "id":"o" 
    },
 */
const setParams = (data, _url, configPageParams) => {
  const obj = {};
  let url = _url;
  console.log(data, '=======>>>>>>>>>>', configPageParams);

  Object.keys(data).forEach(key => {
    // 把值设置到请求地址上
    if (data[key].includes('url=>')) {
      const _key = data[key].replace('url=>', '');
      const value = getNestedProperty(_key, { configPageParams });
      url += `/${value}`;
      obj[key] = value;
    } else if (data[key].includes('$')) {
      // 把动态参数设置到参数中
      const _key = data[key].replace('$', '');
      obj[key] = getNestedProperty(_key, { configPageParams });
    } else {
      // 静态参数
      obj[key] = data[key];
    }
  });
  console.log(obj, '-------------->>>>>>>>>');

  return {
    url,
    params: obj
  };
};

/**
 * 获取对象中属性的值
 * 例如 path = 'a.b.c'
 * 返回 obj.a.b.c
 */
const getNestedProperty = (path: string, obj: any) => {
  const pathArray = path.split('.');
  let current = obj;

  for (let i = 0; i < pathArray.length; i++) {
    if (current === undefined || current === null) {
      return undefined;
    }
    current = current[pathArray[i]];
  }

  return current;
};
